package com.example.qimo

import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class FavoriteCitiesActivity : AppCompatActivity() {
    private lateinit var sharedPreferences: SharedPreferences
    private val refreshReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            refreshFavorites()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_favorite_cities)

        sharedPreferences = getSharedPreferences("AppPrefs", Context.MODE_PRIVATE)

        refreshFavorites()

        val listView = findViewById<ListView>(R.id.listView_favorite_cities)
        listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            val cityCode = getFavoriteCities().entries.find { it.value == cityNames[position] }?.key
            if (cityCode != null) {
                val intent = Intent(this, Main2Activity::class.java)
                intent.putExtra("city_code", cityCode)
                startActivity(intent)
            }
        }

        listView.setOnItemLongClickListener { _, _, position, _ ->
            val cityCode = getFavoriteCities().entries.find { it.value == cityNames[position] }?.key
            if (cityCode != null) {
                showDeleteConfirmationDialog(cityCode)
            }
            true
        }
    }

    override fun onResume() {
        super.onResume()
        val intentFilter = IntentFilter("REFRESH_FAVORITE_CITIES")
        LocalBroadcastManager.getInstance(this).registerReceiver(refreshReceiver, intentFilter)
    }

    override fun onPause() {
        super.onPause()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(refreshReceiver)
    }

    private fun refreshFavorites() {
        val favoriteCities = getFavoriteCities()
        cityNames = favoriteCities.values.toList()

        val listView = findViewById<ListView>(R.id.listView_favorite_cities)
        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, cityNames)
        listView.adapter = adapter
    }

    private fun getFavoriteCities(): Map<String, String> {
        val jsonString = sharedPreferences.getString("favorite_cities", "{}")
        return Gson().fromJson(jsonString, object : TypeToken<Map<String, String>>() {}.type)
    }

    private fun deleteFavoriteCity(cityCode: String) {
        val editor = sharedPreferences.edit()
        val favoriteCities = getFavoriteCities().toMutableMap()
        favoriteCities.remove(cityCode)
        editor.putString("favorite_cities", Gson().toJson(favoriteCities))
        editor.apply()
        Log.d("FavoriteCitiesActivity", "City $cityCode removed from favorites")

        refreshFavorites()
    }

    private fun showDeleteConfirmationDialog(cityCode: String) {
        val cityName = getFavoriteCities()[cityCode] ?: return

        AlertDialog.Builder(this)
            .setTitle("确认删除")
            .setMessage("确定要删除城市 \"$cityName\" 吗？")
            .setPositiveButton("确定") { _, _ ->
                deleteFavoriteCity(cityCode)
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

    companion object {
        private var cityNames = listOf<String>()
    }
}